package com.example.StrJson;

import org.gdal.gdal.gdal;
import org.gdal.ogr.*;

public class Gdal {
    public static void main(String[] args) {
        ogr.RegisterAll();
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
        gdal.SetConfigOption("SHAPE_ENCODING", "CP936");

        String shpDriverName = "ESRI Shapefile";
        org.gdal.ogr.Driver shpDriver = ogr.GetDriverByName(shpDriverName);
        if (shpDriver == null) {
            System.out.println(shpDriverName + " 驱动不可用！\n");
            return;
        }

        String strVectorFile = "D:\\项目数据\\data\\梁溪数据\\2023_江苏省_无锡市-642131_梁溪区\\2023_江苏省_无锡市-642131_梁溪区_餐饮服务.shp";
        DataSource shpDataSource = ogr.Open(strVectorFile, 0);
        if (shpDataSource == null) {
            System.out.println("打开文件【" + strVectorFile + "】失败！");
            return;
        }
        Layer shpLayer = shpDataSource.GetLayerByIndex(0);
        if (shpLayer == null) {
            System.out.println("获取shp图层失败！\n");
            return;
        }
        System.out.println(shpLayer.GetFIDColumn());

        //获取pg驱动
        String pgDriverName = "PostgreSQL";
        org.gdal.ogr.Driver pgDriver = ogr.GetDriverByName(pgDriverName);
        if (pgDriver == null) {
            System.out.println("不支持" + pgDriverName + "驱动");
            return;
        }
        //GDAL连接PostGIS
        String path = "PG:dbname=engine host=192.168.3.2 port=54342 user=postgres password=postgres";
        DataSource pgDataSource = pgDriver.Open(path, 1);
        if (pgDataSource == null) {
            System.out.println("GDAL连接PostGIS数据库失败!");
            return;
        }
        //获取图层
        //Layer pgLayer = pgDataSource.GetLayer(String.valueOf(shpLayer));
        Layer pgLayer = pgDataSource.GetLayerByName(shpLayer.GetName());
        System.out.println(shpLayer.GetName());
        if (pgLayer == null) {
            System.out.println("获取【" + "tablename" + "】图层失败！");
            return;
        }

        Feature oFeature = null;
        while ((oFeature = shpLayer.GetNextFeature()) != null) {
            oFeature.SetFID(100 + oFeature.GetFID());
            System.out.println(oFeature.GetFID());
            pgLayer.CreateFeature(oFeature);
        }
        //写入文件
        pgLayer.SyncToDisk();
        pgDataSource.SyncToDisk();
        //删除数据源
        pgDataSource.delete();
        shpDataSource.delete();
        gdal.GDALDestroyDriverManager();
        System.out.println("shp文件导入成功！");
    }
}
